package com.xtck.ha.fault.framework.kafka;

import com.xtck.ha.fault.framework.utils.JsonResult;
import com.xtck.ha.fault.framework.utils.MessageToJsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

/**
 * @date : 2022-09-23 11:33
 */
@Component
public class KafkaProducer implements IKafkaProducer {
  @Autowired
  private KafkaTemplate<String,String> kafkaTemplate;

  /**
   * 发送消息
   */
  @Override
  public JsonResult<String> send(String topic, PushFaultMsg pushFaultMsg) {
    try{
      //生产消息
      ListenableFuture<SendResult<String, String>> listenableFuture = kafkaTemplate.send(topic, MessageToJsonUtil.toJson(pushFaultMsg));
      listenableFuture.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
        @Override
        public void onSuccess(SendResult<String, String> result) {
          System.out.println("消息发送成功！");
        }
        @Override
        public void onFailure(Throwable ex) {
          System.out.println("消息发送失败！");
        }
      });
      return JsonResult.ok("消息发送成功！");
    }catch (Exception e){
      System.out.println("消息发送异常！");
      return JsonResult.error("消息发送异常！");
    }
  }

}

